package com.nowcoder.community.controller;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.FollowService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;

    /**
     * 获取用户基本信息编辑页面
     * @return
     */
    @LoginRequired
    @RequestMapping(path = "/setting", method = RequestMethod.GET)
    public String getSettingPage() {
        return "/site/setting";
    }

    /**
     * MultipartFile类由SpringMVC提供
     * @param headerImg
     * @return
     */
    @LoginRequired
    @RequestMapping(path = "/upload", method = RequestMethod.POST)
    public String uploadHeader(MultipartFile headerImg, Model model) throws IOException {
        if(headerImg == null) {
            model.addAttribute("error", "您还没有选择图片");
            // 用户没有选择新头像图片
            // 返回设置页
            return "/site/setting";
        }
        String fileName = headerImg.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 检查图片文件后缀
        if(StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件格式不正确!应选择.png或.jpg或.jpeg");
        }
        // 生成随机文件名
        fileName = CommunityUtil.generateUUID() + suffix;
        // 确认文件存放路径
        File file = new File(uploadPath + "/" + fileName);
        try {
            headerImg.transferTo(file);
        } catch(IOException io) {
            logger.error("上传头像文件失败: " + io.getMessage());
            throw new RuntimeException("上传文件异常" + io.getMessage());
        }
        // 更新user表中用户头像路径
        // User对象由HandlerInterception存储到HostHolder中
        int userId = hostHolder.getUsers().getId();
        String fileWebPath = domain + contextPath + "/user/header/" + fileName;
        userService.updateHeader(userId, fileWebPath);
        return "redirect:/index";
    }

    /**
     * 将获取的图片流写入到response
     *
     * @param response
     * @param fileName
     */
    @RequestMapping(path = "/header/{fileName}", method = RequestMethod.GET)
    public void getHeader(HttpServletResponse response, @PathVariable("fileName") String fileName) throws IOException {
        // 服务器存放路径
        fileName = uploadPath + fileName;
        // 获取文件的后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        response.setContentType("image/" + suffix);
        try (FileInputStream inputStream = new FileInputStream(fileName);
             OutputStream os = response.getOutputStream())
        {
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = inputStream.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } catch (IOException io) {
            logger.error("读取头像失败: " + io.getMessage());
        }
    }

    @LoginRequired
    @RequestMapping(path = "/password", method = RequestMethod.POST)
    public String updatePassword(@CookieValue("ticket") String ticket, String originPassword, String newPassword, Model model) {
        User user = hostHolder.getUsers();
        Map<String, Object> msg = userService.updateUserPassword(user, originPassword, newPassword);
        // 修改密码成功
        if(msg == null || msg.isEmpty()) {
            // 退出登录
            userService.logOut(ticket);
            // 重定向至登录页面
            return "redirect:/login";
        }
        // 修改密码失败
        else {
            model.addAttribute("orgPasswordMsg", msg.get("orgPasswordMsg"));
            model.addAttribute("newPasswordMsg", msg.get("newPasswordMsg"));
            // 仍返回设置页面
            return "/site/setting";
        }
    }

    /**
     * 访问个人主页
     * @param targetUserId
     * @param model
     * @return
     */
    @RequestMapping(path = "/profile/{targetUserId}", method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("targetUserId") int targetUserId, Model model) {
        User user = userService.findUserById(targetUserId);
        if(user == null) {
            // 由异常处理切面统一处理
            throw new RuntimeException("用户不存在");
        }
        model.addAttribute("user", user);
        int likeCount = likeService.findUserLikeCount(targetUserId);
        model.addAttribute("likeCount", likeCount);

        // 该用户关注的数量
        long followeeCnt = followService.findFolloweeCount(targetUserId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCnt", followeeCnt);
        // 该用户粉丝的数量
        long followerCnt = followService.findFollowerCount(ENTITY_TYPE_USER, targetUserId);
        model.addAttribute("followerCnt", followerCnt);

        // 是否已关注
        boolean isFollowed = false;
        // 先判断当前发送请求的用户是否登陆
        // 只有登录了, 才能显示用户🌧与主页被查询用户的关系
        if(hostHolder.getUsers() != null) {
            isFollowed = followService.isFollowed(hostHolder.getUsers().getId(), ENTITY_TYPE_USER, targetUserId);
        }
        model.addAttribute("isFollowed", isFollowed);

        return "/site/profile";
    }

}
